<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>守护者</title>
    <link rel="dns-prefetch" href="https://cdn.bootcdn.net/" >
    <link href="https://cdn.bootcdn.net/ajax/libs/mint-ui/2.2.13/style.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.5.16/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/mint-ui/2.2.13/index.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.min.js"></script>
</head>
<body>
    <div id="app">
        <div class="ctrl flex">
            <mt-switch v-model="autoSaveEnabled" @change="autoSaveEnabledChanged">
                <mt-button v-if="autoSaveEnabled" type="primary" plain>自动保存<small>(已开启)</small></mt-button>
                <mt-button v-else type="danger" plain>自动保存<small>(已关闭)</small></mt-button>
            </mt-switch>
            <mt-button type="primary" style="width: calc(45vw)" @click="saveCopy(false)">即时存档</mt-button>
            <mt-button :disabled="files.length===0" type="danger" @click="deleteBatch(files)">清空备份{{files.length>0?`(${files.length})`:''}}</mt-button>
        </div>
        <div class="list flex" style="padding-top: 10px;">
            <div class="files">
                <mt-loadmore :top-method="loadFiles" ref="loadmore" style="min-height: 100%;">
                    <div class="ones-holder">
                        <div class="one" v-for="(file, idx) in files" :key="file"
                             @click="handle(file, file.substr(file.length - 8))"
                        >
                            {{file.substr(file.length - 8)}}
                        </div>
                    </div>
                </mt-loadmore>
            </div>
            <div class="logs">
                <div v-for="l in logs" :key="l.id" class="log">
                    <span style="color:#ccc;">{{l.at}} {{l.event}}</span>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
    function at() {
        const date = new Date();
        const y = date.getFullYear()
        let M = date.getMonth() + 1
        M = M < 10 ? ('0' + M) : M
        let d = date.getDate()
        d = d < 10 ? ('0' + d) : d;
        let h = date.getHours()
        h = h < 10 ? ('0' + h) : h;
        let m = date.getMinutes()
        m = m < 10 ? ('0' + m) : m;
        let s = date.getSeconds()
        s = s < 10 ? ('0' + s) : s;
        return `${y}-${M}-${d} ${h}:${m}:${s}`
    }

    new Vue({
        el: '#app',
        data() {
            return {
                interval: null,
                files: [],
                logs: [],
                autoSaveEnabled: false,
            }
        },
        created() {
            this.loadFiles()
        },
        methods: {
            autoSaveEnabledChanged() {
                if (this.autoSaveEnabled) {
                    this.startAutoSave()
                } else {
                    this.stopAutoSave()
                }
            },
            startAutoSave() {
                const time = at()
                this.logs.unshift({
                    id: time,
                    event: '开启自动备份',
                    at: time
                })
                this.saveCopy(true) // 先保存一次
                this.interval = setInterval(() => {
                    this.saveCopy(true)
                // }, 5 * 1000) // 测试设5秒一次
                }, 3 * 60 * 1000) // 之后开始三分钟自动保存一次
            },
            stopAutoSave() {
                const time = at()
                this.logs.unshift({
                    id: time,
                    event: '停止自动备份',
                    at: time
                })
                clearInterval(this.interval)
                this.interval = null
            },
            handle(file, time) {
                this.$messagebox.confirm(`要怎么处理 ${time} 保存的备份？`, '请选择', {
                    confirmButtonText: '还原',
                    cancelButtonText: '删除'
                }).then(() => {
                    axios.post(`/restore?file=${file}`).then(() => {
                        this.$toast(`已成功还原至：${time}`)
                    }).catch(e => {
                        console.log(e.message)
                        this.$toast('还原操作失败')
                    })
                }).catch(() => {
                    // 选择了删除操作
                    this.deleteBatch(file)
                })
            },
            deleteBatch(files) {
                let msg = `确认删除`
                if (Array.isArray(files)) {
                    msg += `全部的 ${files.length} 条备份？`
                } else {
                    const t = files.substr(files.length - 8)
                    msg += ` ${t} 保存的备份？`
                    files = [files]
                }
                this.$messagebox.confirm(msg, '提示').then(() => {
                    return axios.post('/delete-batch', files)
                }).then(() => {
                    const time = at()
                    this.logs.unshift({
                        id: time,
                        event: `删除了 ${files.length} 条存档`,
                        at: time
                    })
                    this.loadFiles()
                }).catch(() => {
                    console.log('取消了删除操作')
                })
            },
            saveCopy(auto) {
                axios.post('/save-copy').then(res => {
                    this.$toast('保存成功')
                    const time = at()
                    this.logs.unshift({
                        id: time,
                        event: `${auto?'定时自动':'即时手动'} 保存成功`,
                        at: time
                    })
                    return this.loadFiles(true)
                }).catch(e => {
                    this.$toast(e.message)
                })
            },
            loadFiles(quiet) {
                axios.get('/files').then(res => {
                    this.files = res.data
                    this.$refs.loadmore.onTopLoaded()
                    if (!quiet) {
                        this.$toast('已刷新')
                    }
                })
            }
        }
    })
</script>

<style>
    .flex {
        display: flex;
        justify-content: space-between;
    }
    .mint-msgbox {
        width: 50%;
    }
    .files {
        width: 69%;
        border-right: 1px solid #ccc;
        height: calc(100vh - 75px);
        overflow: scroll;
    }
    .ones-holder {
        display: flex;
        flex-wrap: wrap;
        padding: 15px 0 0 15px;
    }
    .one {
        border: 1px solid #C2E7B0;
        border-radius: 4px;
        color: #67C23A;
        background: #F0F9EB;
        font-size: 20px;
        margin: 0 17px 17px 0;
        padding: 12px 16px;
    }
    .logs {
        width: 30%;
        border-left: 1px solid #ccc;
        height: calc(100vh - 75px);
        overflow: scroll;
    }
    .log {
        font-size: 0.8em;
        line-height: 2em;
        text-indent: 2em;
    }
</style>
</html>
